package com.yunhe.abnormal.service.base.impl;

import com.yunhe.abnormal.domain.base.AlarmSmsConfig;
import com.yunhe.abnormal.mapper.base.AlarmSmsConfigMapper;
import com.yunhe.common.model.authority.UserDTO;
import com.yunhe.common.model.base.AlarmSmsConfigDTO;
import com.yunhe.abnormal.repository.base.AlarmSmsConfigRepository;
import com.yunhe.abnormal.service.base.AlarmSmsConfigService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 异常短信接收人配置Service
 * @author liuronglei
 */
@Service
public class AlarmSmsConfigServiceImpl implements AlarmSmsConfigService {
    @Autowired
    private AlarmSmsConfigRepository alarmSmsConfigRepository;
    @Autowired
    private AlarmSmsConfigMapper mapper;

    @Override
    public void update(Long alarmNotifyConfigId, List<AlarmSmsConfigDTO> alarmSmsConfigs) {
        List<AlarmSmsConfig> old = alarmSmsConfigRepository.findByNotifyConfig(alarmNotifyConfigId);
        if (old != null) {
            alarmSmsConfigRepository.deleteAll(old);
        }
        if (alarmSmsConfigs != null) {
            for (int i = 0; i < alarmSmsConfigs.size(); i++) {
                AlarmSmsConfigDTO alarmSmsConfig = alarmSmsConfigs.get(i);
                alarmSmsConfig.setSn((long)(i + 1));
                UserDTO user = alarmSmsConfig.getUser();
                alarmSmsConfig.setUser(null);
                if (user != null) {
                    alarmSmsConfig.setRelatedUserId(user.getId());
                }
                AlarmSmsConfig item = alarmSmsConfigRepository.save(mapper.from(alarmSmsConfig));
                alarmSmsConfigRepository.bindNotifyConfig(item.getId(), alarmNotifyConfigId);
                if (user != null) {
                    alarmSmsConfigRepository.bindUser(item.getId(), user.getId());
                }
            }
        }
    }

    @Override
    public List<AlarmSmsConfigDTO> search(Long alarmNotifyConfigId) {
        return mapper.to(alarmSmsConfigRepository.findByNotifyConfig(alarmNotifyConfigId));
    }
}
